<?php

/*
 * @author Dulshan Kalpage
 * @copyright 2011
 * 
 */

session_start();
//check for form submission
if (isset($_POST['submit']))
{
    $pword = trim($_POST['pword']);
    $pcheck = trim($_POST['cpword']);
    $username = trim($_POST['username']);
    $found = false;

    //for security check that the passwords match
    if ($pword !== $pcheck)
    {
        $result = "Your passwords don't match";
    }
    else
    {
        //all ok so far so lets open the members file
        $membersFile = 'members.txt';
        $file = fopen($membersFile, 'a+');

        //if the file is empty just write to it
        if (filesize($membersFile) === 0)
        {
            fwrite($file, "$username, $pword");
            fclose($file);
            $_SESSION['message'] = "<p><span style='color: green; font-weight: bold;'>Registration complete. Login to enter members area</span></p>";
            header('Location: /Index.php');
        }
        else
        {
            rewind($file);
            while (!feof($file))
            {
                $line = fgets($file);
                $temp = explode(', ', $line);
                if ($temp[0] == $username)
                {
                    $found = true;
                    break;
                }
            }
        }
        //if the username is unique go ahead and write it to file
        if(!$found)
        {
            //add the contents to file
            fwrite($file, "\r\n$username, $pword");			
            fclose($file);			
            $_SESSION['message'] = "<p><span style='color: green; font-weight: bold;'>Registration complete. Login to enter members area</span></p>";
            header('Location: Index.php');
        }
        else
        {
            $_SESSION['message'] = "Username already taken. Choose another one.";
            header('Location: Register.php');
        }
    }
}

?>
